import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Input, 
  Button, 
  Modal, 
  Form, 
  Select, 
  message, 
  Space, 
  Tag, 
  InputNumber, 
  Card, 
  Row, 
  Col, 
  Statistic,
  Drawer,
  Tabs,
  Upload,
  Alert,
  Divider,
  Tooltip,
  Badge
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined, 
  UploadOutlined,
  DatabaseOutlined,
  CodeOutlined,
  SettingOutlined,
  SearchOutlined,
  FilterOutlined,
  DownloadOutlined,
  SyncOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const FactorList = () => {
  const [factors, setFactors] = useState([]);
  const [filteredFactors, setFilteredFactors] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDataSourceDrawerVisible, setIsDataSourceDrawerVisible] = useState(false);
  const [editingFactor, setEditingFactor] = useState(null);
  const [form] = Form.useForm();
  const [dataSourceForm] = Form.useForm();
  const [isAdvancedFilterVisible, setIsAdvancedFilterVisible] = useState(false);
  const [filterForm] = Form.useForm();

  // 模拟所有公募基金因子数据
  const mockFactors = [
    { 
      id: 1, 
      name: '动量因子', 
      type: '技术因子', 
      desc: '基于价格动量的技术分析因子',
      formula: 'momentum = (price_t - price_t-20) / price_t-20',
      category: '技术分析',
      subCategory: '价格动量',
      weight: 0.3,
      status: 'active',
      dataSource: 'Wind',
      updateFrequency: '日频',
      coverage: 3500,
      lastUpdate: '2024-01-15',
      pythonScript: 'momentum_factor.py'
    },
    { 
      id: 2, 
      name: '价值因子', 
      type: '基本面因子', 
      desc: '基于估值指标的基本面因子',
      formula: 'value = (book_value / market_value)',
      category: '基本面',
      subCategory: '估值',
      weight: 0.4,
      status: 'active',
      dataSource: 'Choice',
      updateFrequency: '日频',
      coverage: 3200,
      lastUpdate: '2024-01-15',
      pythonScript: 'value_factor.py'
    },
    { 
      id: 3, 
      name: '规模因子', 
      type: '风险因子', 
      desc: '基于公司规模的系统性风险因子',
      formula: 'size = log(market_cap)',
      category: '风险控制',
      subCategory: '规模风险',
      weight: 0.2,
      status: 'active',
      dataSource: 'Wind',
      updateFrequency: '日频',
      coverage: 3800,
      lastUpdate: '2024-01-15',
      pythonScript: 'size_factor.py'
    },
    { 
      id: 4, 
      name: '质量因子', 
      type: '基本面因子', 
      desc: '基于公司盈利质量的基本面因子',
      formula: 'quality = (roe * 0.4 + debt_to_equity * 0.3 + asset_turnover * 0.3)',
      category: '基本面',
      subCategory: '盈利质量',
      weight: 0.25,
      status: 'active',
      dataSource: 'Choice',
      updateFrequency: '季频',
      coverage: 2800,
      lastUpdate: '2024-01-10',
      pythonScript: 'quality_factor.py'
    },
    { 
      id: 5, 
      name: '波动率因子', 
      type: '风险因子', 
      desc: '基于历史波动率的风险因子',
      formula: 'volatility = std(returns_60d)',
      category: '风险控制',
      subCategory: '波动风险',
      weight: 0.15,
      status: 'active',
      dataSource: 'Wind',
      updateFrequency: '日频',
      coverage: 3500,
      lastUpdate: '2024-01-15',
      pythonScript: 'volatility_factor.py'
    },
    { 
      id: 6, 
      name: '成长因子', 
      type: '基本面因子', 
      desc: '基于公司成长性的基本面因子',
      formula: 'growth = (revenue_growth * 0.5 + earnings_growth * 0.5)',
      category: '基本面',
      subCategory: '成长性',
      weight: 0.3,
      status: 'active',
      dataSource: 'Choice',
      updateFrequency: '季频',
      coverage: 2600,
      lastUpdate: '2024-01-10',
      pythonScript: 'growth_factor.py'
    },
    { 
      id: 7, 
      name: '流动性因子', 
      type: '技术因子', 
      desc: '基于交易流动性的技术因子',
      formula: 'liquidity = log(turnover_rate * avg_volume)',
      category: '技术分析',
      subCategory: '流动性',
      weight: 0.2,
      status: 'active',
      dataSource: 'Wind',
      updateFrequency: '日频',
      coverage: 3500,
      lastUpdate: '2024-01-15',
      pythonScript: 'liquidity_factor.py'
    },
    { 
      id: 8, 
      name: 'Beta因子', 
      type: '风险因子', 
      desc: '基于市场敏感性的风险因子',
      formula: 'beta = cov(returns, market_returns) / var(market_returns)',
      category: '风险控制',
      subCategory: '市场风险',
      weight: 0.1,
      status: 'active',
      dataSource: 'Wind',
      updateFrequency: '日频',
      coverage: 3500,
      lastUpdate: '2024-01-15',
      pythonScript: 'beta_factor.py'
    }
  ];

  // 数据源配置选项
  const dataSources = ['Wind', 'Choice', 'Bloomberg', 'Reuters', '自定义'];
  const factorTypes = ['技术因子', '基本面因子', '风险因子', '宏观因子', '另类因子'];
  const factorCategories = ['技术分析', '基本面', '风险控制', '宏观分析', '另类数据'];
  const updateFrequencies = ['日频', '周频', '月频', '季频', '年频'];

  useEffect(() => {
    const stored = localStorage.getItem('factorListData');
    if (stored) {
      const data = JSON.parse(stored);
      setFactors(data);
      setFilteredFactors(data);
    } else {
      setFactors(mockFactors);
      setFilteredFactors(mockFactors);
    }
  }, []);

  const columns = [
    { 
      title: '因子名称', 
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{name}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.subCategory}</div>
        </div>
      ),
    },
    { 
      title: '类型', 
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => <Tag color="blue">{type}</Tag>,
    },
    { 
      title: '分类', 
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => <Tag color="green">{category}</Tag>,
    },
    { 
      title: '数据源', 
      dataIndex: 'dataSource',
      key: 'dataSource',
      width: 100,
      render: (source) => <Tag color="orange">{source}</Tag>,
    },
    { 
      title: '更新频率', 
      dataIndex: 'updateFrequency',
      key: 'updateFrequency',
      width: 100,
    },
    { 
      title: '覆盖基金数', 
      dataIndex: 'coverage',
      key: 'coverage',
      width: 120,
      render: (coverage) => <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{coverage}</span>,
    },
    { 
      title: '权重', 
      dataIndex: 'weight',
      key: 'weight',
      width: 80,
      render: (weight) => `${(weight * 100).toFixed(0)}%`,
    },
    { 
      title: '状态', 
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Badge 
          status={status === 'active' ? 'success' : 'error'} 
          text={status === 'active' ? '启用' : '停用'} 
        />
      ),
    },
    { 
      title: '最后更新', 
      dataIndex: 'lastUpdate',
      key: 'lastUpdate',
      width: 120,
    },
    { 
      title: '操作', 
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="编辑因子">
            <Button 
              type="link" 
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="删除因子">
            <Button 
              type="link" 
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingFactor(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingFactor(record);
    form.setFieldsValue({
      ...record,
      weight: record.weight * 100 // 转换为百分比
    });
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个因子吗？删除后无法恢复。',
      onOk: () => {
        const newFactors = factors.filter(factor => factor.id !== id);
        setFactors(newFactors);
        setFilteredFactors(filteredFactors.filter(factor => factor.id !== id));
        localStorage.setItem('factorListData', JSON.stringify(newFactors));
        message.success('删除成功');
      },
    });
  };

  const handleViewDetails = (record) => {
    Modal.info({
      title: `${record.name} - 因子详情`,
      width: 800,
      content: (
        <div>
          <Row gutter={16}>
            <Col span={12}>
              <Card size="small" title="基本信息">
                <p><strong>因子名称：</strong>{record.name}</p>
                <p><strong>因子类型：</strong>{record.type}</p>
                <p><strong>因子分类：</strong>{record.category}</p>
                <p><strong>子分类：</strong>{record.subCategory}</p>
                <p><strong>因子权重：</strong>{(record.weight * 100).toFixed(0)}%</p>
                <p><strong>因子状态：</strong>{record.status === 'active' ? '启用' : '停用'}</p>
              </Card>
            </Col>
            <Col span={12}>
              <Card size="small" title="数据信息">
                <p><strong>数据源：</strong>{record.dataSource}</p>
                <p><strong>更新频率：</strong>{record.updateFrequency}</p>
                <p><strong>覆盖基金数：</strong>{record.coverage}</p>
                <p><strong>最后更新：</strong>{record.lastUpdate}</p>
                <p><strong>Python脚本：</strong>{record.pythonScript}</p>
              </Card>
            </Col>
          </Row>
          <Card size="small" title="因子描述" style={{ marginTop: '16px' }}>
            <p>{record.desc}</p>
          </Card>
          <Card size="small" title="计算公式" style={{ marginTop: '16px' }}>
            <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', fontSize: '14px' }}>
              {record.formula}
            </pre>
          </Card>
        </div>
      ),
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const factorData = {
        ...values,
        weight: values.weight / 100, // 转换为小数
        status: 'active',
        lastUpdate: new Date().toISOString().split('T')[0],
        coverage: values.coverage || 0,
        pythonScript: values.pythonScript || `${values.name.toLowerCase().replace(/\s+/g, '_')}_factor.py`
      };

      if (editingFactor) {
        // 编辑模式
        const updatedFactors = factors.map(factor => 
          factor.id === editingFactor.id ? { ...factor, ...factorData } : factor
        );
        setFactors(updatedFactors);
        setFilteredFactors(updatedFactors);
        localStorage.setItem('factorListData', JSON.stringify(updatedFactors));
        message.success('因子更新成功');
      } else {
        // 新增模式
        const newFactor = {
          id: Date.now(),
          ...factorData,
        };
        const updatedFactors = [...factors, newFactor];
        setFactors(updatedFactors);
        setFilteredFactors(updatedFactors);
        localStorage.setItem('factorListData', JSON.stringify(updatedFactors));
        message.success('因子添加成功');
      }
      
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  const handleSearch = (value) => {
    setSearchText(value);
    if (!value) {
      setFilteredFactors(factors);
    } else {
      const filtered = factors.filter(factor => 
        factor.name.toLowerCase().includes(value.toLowerCase()) ||
        factor.type.toLowerCase().includes(value.toLowerCase()) ||
        factor.category.toLowerCase().includes(value.toLowerCase()) ||
        factor.dataSource.toLowerCase().includes(value.toLowerCase()) ||
        factor.desc.toLowerCase().includes(value.toLowerCase())
      );
      setFilteredFactors(filtered);
    }
  };

  const handleAdvancedFilter = async () => {
    try {
      const values = await filterForm.validateFields();
      let filtered = factors;

      // 应用各种筛选条件
      if (values.factorType && values.factorType.length > 0) {
        filtered = filtered.filter(factor => values.factorType.includes(factor.type));
      }

      if (values.category && values.category.length > 0) {
        filtered = filtered.filter(factor => values.category.includes(factor.category));
      }

      if (values.dataSource && values.dataSource.length > 0) {
        filtered = filtered.filter(factor => values.dataSource.includes(factor.dataSource));
      }

      if (values.status) {
        filtered = filtered.filter(factor => factor.status === values.status);
      }

      if (values.updateFrequency && values.updateFrequency.length > 0) {
        filtered = filtered.filter(factor => values.updateFrequency.includes(factor.updateFrequency));
      }

      if (values.coverageRange && values.coverageRange.length === 2) {
        filtered = filtered.filter(factor => 
          factor.coverage >= values.coverageRange[0] && factor.coverage <= values.coverageRange[1]
        );
      }

      setFilteredFactors(filtered);
      setIsAdvancedFilterVisible(false);
      message.success(`筛选完成，共找到 ${filtered.length} 个因子`);
    } catch (error) {
      console.error('筛选失败:', error);
    }
  };

  const handleClearFilter = () => {
    filterForm.resetFields();
    setFilteredFactors(factors);
    setSearchText('');
    message.success('筛选条件已清除');
  };

  const handleDataSourceConfig = async () => {
    try {
      const values = await dataSourceForm.validateFields();
      message.success('数据源配置成功');
      setIsDataSourceDrawerVisible(false);
      dataSourceForm.resetFields();
    } catch (error) {
      console.error('数据源配置失败:', error);
    }
  };

  const handleDataSync = () => {
    message.loading('正在同步数据...', 2).then(() => {
      message.success('数据同步完成');
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总因子数" 
              value={filteredFactors.length} 
              prefix={<DatabaseOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="启用因子" 
              value={filteredFactors.filter(f => f.status === 'active').length} 
              prefix={<CodeOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="数据源数" 
              value={new Set(filteredFactors.map(f => f.dataSource)).size} 
              prefix={<SettingOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均覆盖基金" 
              value={filteredFactors.length > 0 ? 
                Math.round(filteredFactors.reduce((sum, f) => sum + f.coverage, 0) / filteredFactors.length) : 0
              } 
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和操作栏 */}
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
          <Input.Search
            placeholder="输入因子名称/类型/分类/数据源"
            style={{ width: 400 }}
            onSearch={handleSearch}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <Button 
            icon={<FilterOutlined />}
            onClick={() => setIsAdvancedFilterVisible(true)}
          >
            高级筛选
          </Button>
        </div>
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button 
            icon={<SyncOutlined />}
            onClick={handleDataSync}
          >
            同步数据
          </Button>
          <Button 
            icon={<SettingOutlined />}
            onClick={() => setIsDataSourceDrawerVisible(true)}
          >
            数据源配置
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增因子
          </Button>
        </div>
      </div>

      {/* 因子列表 */}
      <Table 
        dataSource={filteredFactors} 
        columns={columns} 
        rowKey="id"
        loading={loading}
        pagination={{
          total: filteredFactors.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        scroll={{ x: 1500 }}
      />

      {/* 新增/编辑因子模态框 */}
      <Modal
        title={editingFactor ? '编辑因子' : '新增因子'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ weight: 30, status: 'active' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="因子名称"
                rules={[{ required: true, message: '请输入因子名称' }]}
              >
                <Input placeholder="请输入因子名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="因子类型"
                rules={[{ required: true, message: '请选择因子类型' }]}
              >
                <Select placeholder="请选择因子类型">
                  {factorTypes.map(type => (
                    <Option key={type} value={type}>{type}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="category"
                label="因子分类"
                rules={[{ required: true, message: '请选择因子分类' }]}
              >
                <Select placeholder="请选择因子分类">
                  {factorCategories.map(category => (
                    <Option key={category} value={category}>{category}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="subCategory"
                label="子分类"
                rules={[{ required: true, message: '请输入子分类' }]}
              >
                <Input placeholder="请输入子分类" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="dataSource"
                label="数据源"
                rules={[{ required: true, message: '请选择数据源' }]}
              >
                <Select placeholder="请选择数据源">
                  {dataSources.map(source => (
                    <Option key={source} value={source}>{source}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="updateFrequency"
                label="更新频率"
                rules={[{ required: true, message: '请选择更新频率' }]}
              >
                <Select placeholder="请选择更新频率">
                  {updateFrequencies.map(freq => (
                    <Option key={freq} value={freq}>{freq}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="weight"
                label="权重(%)"
                rules={[{ required: true, message: '请输入权重' }]}
              >
                <InputNumber 
                  min={0} 
                  max={100} 
                  style={{ width: '100%' }}
                  placeholder="请输入权重百分比"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="coverage"
                label="覆盖基金数"
                rules={[{ required: true, message: '请输入覆盖基金数' }]}
              >
                <InputNumber 
                  min={0} 
                  style={{ width: '100%' }}
                  placeholder="请输入覆盖基金数"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="desc"
            label="因子描述"
            rules={[{ required: true, message: '请输入因子描述' }]}
          >
            <TextArea 
              rows={3}
              placeholder="请输入因子描述"
            />
          </Form.Item>

          <Form.Item
            name="formula"
            label="计算公式"
            rules={[{ required: true, message: '请输入计算公式' }]}
          >
            <TextArea 
              rows={4}
              placeholder="请输入计算公式"
            />
          </Form.Item>

          <Form.Item
            name="pythonScript"
            label="Python脚本文件名"
          >
            <Input placeholder="请输入Python脚本文件名（可选）" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 数据源配置抽屉 */}
      <Drawer
        title="数据源配置"
        placement="right"
        width={600}
        open={isDataSourceDrawerVisible}
        onClose={() => setIsDataSourceDrawerVisible(false)}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setIsDataSourceDrawerVisible(false)} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button type="primary" onClick={handleDataSourceConfig}>
              保存配置
            </Button>
          </div>
        }
      >
        <Tabs defaultActiveKey="1">
          <TabPane tab="配置化接入" key="1">
            <Form form={dataSourceForm} layout="vertical">
              <Form.Item
                name="dataSourceName"
                label="数据源名称"
                rules={[{ required: true, message: '请输入数据源名称' }]}
              >
                <Select placeholder="选择数据源">
                  <Option value="Wind">Wind金融终端</Option>
                  <Option value="Choice">Choice金融终端</Option>
                  <Option value="Bloomberg">Bloomberg终端</Option>
                  <Option value="Reuters">Reuters终端</Option>
                  <Option value="custom">自定义数据源</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="apiKey"
                label="API密钥"
                rules={[{ required: true, message: '请输入API密钥' }]}
              >
                <Input.Password placeholder="请输入API密钥" />
              </Form.Item>

              <Form.Item
                name="endpoint"
                label="接口地址"
                rules={[{ required: true, message: '请输入接口地址' }]}
              >
                <Input placeholder="请输入接口地址" />
              </Form.Item>

              <Form.Item
                name="updateInterval"
                label="更新间隔"
                rules={[{ required: true, message: '请选择更新间隔' }]}
              >
                <Select placeholder="选择更新间隔">
                  <Option value="daily">每日</Option>
                  <Option value="weekly">每周</Option>
                  <Option value="monthly">每月</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="dataFields"
                label="数据字段配置"
              >
                <TextArea 
                  rows={6}
                  placeholder="请输入数据字段配置（JSON格式）"
                />
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="Python脚本接入" key="2">
            <Alert
              message="Python脚本接入"
              description="支持通过Python脚本方式接入复杂数据，可快速实现对复杂数据的加工处理。"
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
            
            <Form layout="vertical">
              <Form.Item label="上传Python脚本">
                <Upload
                  name="pythonScript"
                  action="/api/upload-script"
                  accept=".py"
                  maxCount={1}
                >
                  <Button icon={<UploadOutlined />}>上传Python脚本</Button>
                </Upload>
              </Form.Item>

              <Form.Item label="脚本配置">
                <TextArea 
                  rows={8}
                  placeholder="请输入脚本配置参数（JSON格式）"
                />
              </Form.Item>

              <Form.Item label="依赖包">
                <TextArea 
                  rows={4}
                  placeholder="请输入所需的Python依赖包"
                />
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="数据测试" key="3">
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <Button type="primary" size="large" icon={<SyncOutlined />}>
                测试数据连接
              </Button>
              <div style={{ marginTop: '16px', color: '#666' }}>
                点击按钮测试数据源连接是否正常
              </div>
            </div>
          </TabPane>
        </Tabs>
      </Drawer>

      {/* 高级筛选抽屉 */}
      <Drawer
        title="高级筛选"
        placement="right"
        width={500}
        open={isAdvancedFilterVisible}
        onClose={() => setIsAdvancedFilterVisible(false)}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={handleClearFilter} style={{ marginRight: 8 }}>
              清除筛选
            </Button>
            <Button type="primary" onClick={handleAdvancedFilter}>
              应用筛选
            </Button>
          </div>
        }
      >
        <Form form={filterForm} layout="vertical">
          <Form.Item
            name="factorType"
            label="因子类型"
          >
            <Select
              mode="multiple"
              placeholder="选择因子类型"
              allowClear
              style={{ width: '100%' }}
            >
              {factorTypes.map(type => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="category"
            label="因子分类"
          >
            <Select
              mode="multiple"
              placeholder="选择因子分类"
              allowClear
              style={{ width: '100%' }}
            >
              {factorCategories.map(category => (
                <Option key={category} value={category}>{category}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="dataSource"
            label="数据源"
          >
            <Select
              mode="multiple"
              placeholder="选择数据源"
              allowClear
              style={{ width: '100%' }}
            >
              {dataSources.map(source => (
                <Option key={source} value={source}>{source}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
          >
            <Select placeholder="选择状态" allowClear style={{ width: '100%' }}>
              <Option value="active">启用</Option>
              <Option value="inactive">停用</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="updateFrequency"
            label="更新频率"
          >
            <Select
              mode="multiple"
              placeholder="选择更新频率"
              allowClear
              style={{ width: '100%' }}
            >
              {updateFrequencies.map(freq => (
                <Option key={freq} value={freq}>{freq}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="coverageRange"
            label="覆盖基金数范围"
          >
            <Input.Group compact>
              <Form.Item noStyle name={['coverageRange', 0]}>
                <InputNumber
                  placeholder="最小值"
                  style={{ width: '50%' }}
                  min={0}
                />
              </Form.Item>
              <Form.Item noStyle name={['coverageRange', 1]}>
                <InputNumber
                  placeholder="最大值"
                  style={{ width: '50%' }}
                  min={0}
                />
              </Form.Item>
            </Input.Group>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default FactorList; 